package top.maof.book.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {

    private static final String SIGNATURE = "11111111111111145vfdbvfdsncsjklsxnSLxnKLSNxaklsnxlkSNklsczncknxjmsoxjamo";

    // 默认有效时间 3小时
    public static final Integer HOUR = 7 * 24;

    public static String getToken(Map<String, String> map) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, HOUR);
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> builder.withClaim(k, v));
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SIGNATURE));
        return token;
    }

    public static String getToken() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, HOUR);
        JWTCreator.Builder builder = JWT.create();
        String token = builder.withExpiresAt(calendar.getTime()).sign(Algorithm.HMAC256(SIGNATURE));
        return token;
    }

    public static boolean checkToken(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private static Map<String, Claim> parseToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SIGNATURE);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            Map<String, Claim> claims = jwt.getClaims();
            return claims;
        } catch (Exception e) {
            return null;
        }
    }

    public static String parseToken(String token, String key) {
        try {
            Map<String, Claim> claims = parseToken(token);
            if (claims.containsKey(key)) {
                Claim claim = claims.get(key);
                return claim.asString();
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }

    public static Integer getUserId(String token) {
        return Integer.parseInt(parseToken(token, "id"));
    }
}
